
import 'package:bot_toast/bot_toast.dart';
import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/friend_apply_list_entity.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/address_book/address_list_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/new_friend/new_friend_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/util/rong_widget.dart';
import 'package:flutter_ncsjqz_getx/page_common/scan/scan_page.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../conversation_list/rong_colud_session_list_logic.dart';
import '../util/rong_constant.dart';
import '../util/rong_widget.dart';
import 'isolate/isolate_view.dart';
import 'my_code_page.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/11 15:19
/// filePath： lib/page/rong_im/rong_colud_session_list_view.dart
/// desc: 融云 会话列表
/// <summary>
///
class RongColudSessionListPage extends StatefulWidget {
  @override
  _RongColudSessionListPageState createState() => _RongColudSessionListPageState();
}

class _RongColudSessionListPageState extends State<RongColudSessionListPage> {
  final logic = Get.put(RongColudSessionListLogic());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    logic.init();
  }


  @override
  void didChangeDependencies() {
    // 更新融云会话列表
    logic.getConversationList();
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RongColudSessionListLogic>(
      builder: (controller) {
        return Scaffold(
          body: GestureDetector(
            onTapDown: (v)=>FocusScope.of(context).requestFocus(FocusNode()),
            child: Column(
              children: [
                header(),
                listView(),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 会话列表
  Widget listView() {
    return Expanded(
      child: Padding(
        child: RongWidget.baseScaffoldWidget(
          onRefresh: () async{
            logic.getConversationList();
          },
          child: ListView.separated(
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.all(0),
            itemBuilder: (ctx,index){
              return sessionItem(index);
            },
            separatorBuilder: (BuildContext context, int index) {
              return Divider(height: 1,color: Colors.grey.shade300,);
            },
            itemCount: logic.contentList.length,
          ),
        ),
        padding: EdgeInsets.symmetric(horizontal: 15,),
      ),
    );
  }

  /// 头部背景
  Widget header() {
    return Container(
      width: Get.width,
      height: 90,
      padding: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.cover,
          image: AssetImage(RongConstant.getLocalImg("head_bg.png"),),
        ),
      ),
      child: SafeArea(
        child: appBar(),
      ),
    );
  }

  /// 头部菜单栏
  Widget appBar(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          width: Get.width / 3,
        ),
        RongWidget.text("对 话",color: Colors.white,fonSize: 18),
        Container(
          width: Get.width / 3,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 好友列表
              RongWidget.imgAsset("list.png",width: 20,onTap: (){
                  Get.to(()=>AddressListPage(type: 0,));
                },padding: EdgeInsets.all(15),
              ),
              SizedBox(width: 5,),
              // 右上角悬浮菜单
              CustomPopupMenu(
                controller: logic.menuController,
                barrierColor: Colors.transparent,
                child: RongWidget.imgAsset("add.png",width: 20),
                menuBuilder: (){
                  return bodyList();
                },
                pressType: PressType.singleClick,
                arrowColor: Colors.white,
                verticalMargin: -5,
                arrowSize: 15,
              ),
            ],
          ),
        ),
      ],
    );
  }

  bodyList() {
    // 获取好友申请数
    int tj = 0;
    DioService<FriendApplyListEntity>().friendApplyList().then((value) {
      if(value!.code == 0)
        value.data!.forEach((element) {
          if(element.friendType == 0) tj++;
        });
      logic.update();
    });
    return GetBuilder<RongColudSessionListLogic>(
      builder: (con){
        return Container(
          child: Column(
            children: logic.menuItems.map((e){
              return InkWell(
                child: Container(
                  width: 130,
                  padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // data
                      Stack(
                        overflow: Overflow.visible,
                        children: [
                          RongWidget.imgAsset("${e.icon}",width: 20,color: Colors.green),
                          e.title == "添加好友" && tj != 0?Positioned(
                            top: -10,
                            right: -10,
                            child: ClipOval(
                            child: Container(
                              width: 15,
                              height: 15,
                              alignment: Alignment.center,
                              child: InkWidget.text("$tj",color: Colors.white),
                              color: Colors.red ,
                            ),
                          ),):SizedBox(),
                        ],
                      ),
                      RongWidget.text("  ${e.title}"),
                    ],
                  ),
                ),
                onTap: () async{
                  logic.menuClose();
                  switch(e.title){
                    case "发起群聊":
                      Get.to(()=>AddressListPage(type: 1,))!.then((value){
                        print(value);
                        if(value!=null) logic.createRongGroup(value);
                      });
                      break;
                    case "自我隔离":
                      Get.to(()=>IsolatePage());
                      break;
                    case "扫一扫":
                      if(await Permission.camera.request().isGranted){
                        Get.to(() => ScanPage(),preventDuplicates: false)!.then((value) {
                          print("扫码结果 $value");
                          if(value!=null){
                            logic.scanCode(value);
                          }
                        });
                      }else{
                        BotToast.showText(text: "当前么有相机权限，无法启动扫码");
                      }
                      break;
                    case "我的二维码":
                      Get.to(() => MyCodePage(),preventDuplicates: false);
                      break;
                    case "添加好友":
                      Get.to(() => NewFriendPage(),preventDuplicates: false);
                      break;
                  }
                },
              );
            }).toList(),
          ),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                  color: Colors.grey.shade400,
                  blurRadius: 2.2,
                  spreadRadius: 2.2
              ),
            ],
          ),
        );
      },
    );
  }
  /// 会话列表->item
  Widget sessionItem(index) {
    return InkWell(
      onTap: (){
        print("进入聊天页面");
        logic.openChat(index);
      },
      child: ListTile(
        leading: Stack(
          overflow: Overflow.visible,
          children: [
            /// 群聊头像 or 单聊头像
            logic.contentList[index].menuMessageType == 2 ? rongGroupPic(index) : rongOnePic(index),
            /// 未读消息数量
            Positioned(
              top: -8,
              right: -8,
              child: ClipOval(
                child: Container(
                  width: 23,
                  height: 23,
                  color:logic.contentList[index].count == 0 ? Colors.transparent : Colors.red,
                  alignment: Alignment.center,
                  child: RongWidget.text("${logic.contentList[index].count}",color: Colors.white,fonSize: 12),
                ),
              ),
            ),
          ],
        ),
        title: RongWidget.title("${logic.contentList[index].nickName}"),
        subtitle: RongWidget.text("${logic.contentList[index].message}",color: Colors.grey.shade600),
        trailing: RongWidget.text("${logic.contentList[index].timer}",color: Colors.grey),
        contentPadding: EdgeInsets.symmetric(horizontal: 0,vertical: 5),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<RongColudSessionListLogic>();
    // if(logic.menuController!=null) logic.menuController.dispose();
    // RongBaseLogic.disconnect(false);
    super.dispose();
  }

  /// 群聊头像
  rongGroupPic(index) {
    // 成员数
    int picMax = logic.contentList[index].urls!.length;
    double height = 0.0;
    if(picMax >= 3){
      height = 50 / 3;
    }
    if(picMax == 2 || picMax == 3 || picMax == 4){
      height = 50 / 2;
    }
    if(picMax == 1){
      height = 50;
    }
    return Container(
      width: 60,
      height: 60,
      child: Wrap(
        alignment: picMax == 3 ? WrapAlignment.center : WrapAlignment.start,
        runAlignment: picMax == 2 || picMax == 6 || picMax == 3 ? WrapAlignment.center : WrapAlignment.start,
        runSpacing: 10,
        spacing: 10,
        children: List.generate(picMax, (id){
          return RongWidget.imgNet('${logic.contentList[index].urls![id] ?? ""}',width: height ,height: height ,borderRadius: BorderRadius.circular(2));
        }),
      ),
    );
  }

  /// 单聊头像
  rongOnePic(index) {
    return RongWidget.imgNet("${logic.contentList[index].cover}",width: 60,height: 60,borderRadius: BorderRadius.circular(5));
  }

}